package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-13
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        //构建查询条件
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        //根据文章状态查询
        if (dto.getStatus()!=null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        //根据关键字模糊查询文章标题
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        //根据频道列表查询
        if (dto.getChannelId()!=null) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //发布日期  开始日期  结束日期
        if (dto.getBeginPubDate()!=null) {
            query.gt(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate()!=null) {
            query.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }
        //当前用户
        User user = MediaThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        query.eq(WmNews::getUserId, user.getUserId());
        //按照文章发布时间倒叙排列
        query.orderByDesc(WmNews::getPublishTime);
        //构建分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //分页查询文章列表
        IPage<WmNews> iPage = this.page(page, query);
        //构建通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }
//发布文章
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //保存草稿.提交审核 更新文章 统一接口
        //用户id从本地线程获取
        User user = MediaThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断dto中文章id是否为空
        //不为空 走更新的操作 删除已有的文章和素材对应关系,重新保存文章及文章和图片扥关联关系
        if (dto.getId()!=null) {
            //删除已有文章和素材的关系
            removeRelation(dto.getId());
        }
        //id为空新增文章
        //构建文章对象
        WmNews wmNews = new WmNews();
        //相同字段通过工具复制
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //封面图片转换为JSON存储
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        //如果前端传入的封面类型是自动的,封面图片从内容中选取
        //从文章内容中提取图片列表
        List<ImageDto> contentImage = getImagesFormContent(wmNews.getContent());
        if (dto.getType()==-1) {
            //判断内容图片的数量
            //内容无图设置封面类型为零\
            //内容图片数量小于三张,设置封面类型是一,并取内容中第一章图片为封面
            //内容图片大于三,设置封面类型为3,截取内容图片的前三张为封面
            if (contentImage.size() <= 0) {
                wmNews.setType(0);
            } else if (contentImage.size() < 3) {
                wmNews.setType(1);
                List<ImageDto> coverImages = contentImage.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(coverImages));
            } else {
                wmNews.setType(3);
                List<ImageDto> coverImages = contentImage.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(coverImages));
            }
        }
            //进行保存
            //this.save(wmNews)
            this.saveOrUpdate(wmNews);
            //需要判断是保存草稿还是提交审核
            if (dto.getStatus()==1) {
                //如果提交审核,需要保存文章和素材的关系
                //包含内容图片的关联和封面图片的关系
                //保存封面图片和素材表的关联关系
                List<ImageDto> coverImages = JSON.parseArray(wmNews.getImages(), ImageDto.class);
                saveRelation(coverImages, 1, wmNews.getId());
                //保存图片和内容和素材表的关联关系
                saveRelation(contentImage, 0, wmNews.getId());
                //开启自动审核文章,异步处理
                System.out.println("开始调用自动审核服务");
                auditService.audit(wmNews);
                System.out.println("自动审核服务调用完成");
            }

        return ResponseResult.okResult();
    }
//上下架
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //根据id查询文章
        WmNews wmNews = this.getById(dto.getId());
        //判断文章是否存在
        if (wmNews==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章是否已发布
        if (wmNews.getStatus()!=9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //修改上下架状态\
        wmNews.setEnable((dto.getEnable() == 1) ? true : false);
        this.updateById(wmNews);
        //同步到app
        //发送到消息中间件
        String key = wmNews.getArticleId().toString();

        String value = (dto.getEnable() == 1) ? "false" : "true";
        kafkaTemplate.send(upDownTopic, key, value);

        return ResponseResult.okResult();
    }
    //文章列表查询
    @Override
    public ResponseResult findPageByName(WmNewsPageDto dto) {
        //构建查询条件
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            // 根据文章标题模糊查询
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getChannelId() != null) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null) {
            query.gt(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            query.lt(WmNews::getPublishTime, dto.getEndPubDate());
        }
        // 根据文章的发布时间倒序排列
        query.orderByDesc(WmNews::getPublishTime);
        // 分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> iPage = this.page(page, query);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        return result;
    }

    //查询文章详情
    @Override
    public ResponseResult findNewsVoById(Integer id) {
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        query.eq(WmNews::getId, id);
        WmNews wmNews = this.getById(id);
        return ResponseResult.okResult(wmNews);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;
    @Autowired
    @Lazy//懒加载
    private IAuditService auditService;



    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    //删除已有的文章和素材的关系
    private void removeRelation(Integer newsId) {
        LambdaQueryWrapper<WmNewsMaterial> query = new LambdaQueryWrapper<>();
        query.eq(WmNewsMaterial::getNewsId, newsId);
        newsMaterialService.remove(query);

    }
    //从文章内容中提取图片列表
    private List<ImageDto> getImagesFormContent(String content) {
        List<ImageDto> list = new ArrayList<>();
        //解析JSON内容
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                list.add(imageDto);
            }
        }
        return list;
    }

    //保存文章和素材表的关系
    private void saveRelation(List<ImageDto> images, int type, Integer newsId) {
        int ord = 0;
        for (ImageDto image : images) {
            WmNewsMaterial newsMaterial = new WmNewsMaterial();
            newsMaterial.setMaterialId(image.getId());
            newsMaterial.setNewsId(newsId);
            newsMaterial.setType(type);
            newsMaterial.setOrd(ord++);
            newsMaterialService.save(newsMaterial);
        }
    }



}
